package com.czmh.etc.onlinepubsys.utils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.weixin4j.misc.BASE64Decoder;
import org.weixin4j.misc.BASE64Encoder;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.Date;

@Slf4j
public class ImageZipUtil {

    /**
     * Thumbnailator 是一个优秀的图片处理的Google开源Java类库。
     * 根据指定大小压缩图片
     *
     * @param picPath     源图片路径
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     * @
     */
    public static byte[] compressPicForScale(String picPath, long desFileSize) {
        long srcSize = 0;
        byte[] data = null;
        FileImageInputStream input;
        try {
            input = new FileImageInputStream(new File(picPath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            while (data != null && data.length > desFileSize * 1024) {
                srcSize = data.length;
                double accuracy = getAccuracy(srcSize / 1024);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
                Thumbnails.of(picPath).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
                data = outputStream.toByteArray();
                OutputStream out = new FileOutputStream(picPath);
                InputStream is = new ByteArrayInputStream(data);
                byte[] buff = new byte[1024];
                int len;
                while ((len = is.read(buff)) != -1) {
                    out.write(buff, 0, len);
                }
                is.close();
                out.close();
            }
            log.info(String.format("图片压缩完成: 图片原大小={%d}kb | 压缩后大小={%d}kb", srcSize / 1024, data.length / 1024));
        } catch (Exception e) {
            throw new RuntimeException("图片压缩失败!");
        }
        return data;
    }

    public static String handleAndReduceBase64(String base64) {
        File file = null;
        try {
            file = turnBase64ToTempImageFile(base64, ".jpg");
            //3.大于200k压缩图片
            byte[] compressPic = compressPicForScale(file.getPath(), 800);
            //压缩图片转base64
            return ImageZipUtil.turnByteToBase64(compressPic);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ImageZipUtil.deleteTempImageFile(file);
        }
        return null;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.8;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }

    /**
     * @Description: base64转临时文件
     * @author ljj
     * @date 2021/4/2
     */
    public static File turnBase64ToTempImageFile(String imgBase64, String suffix) throws IOException {
        FileOutputStream outputStream = null;
        try {
            File file;
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] bytes = base64Decoder.decodeBuffer(imgBase64);
            file = File.createTempFile(String.valueOf(new Date().getTime()), suffix);
            //测试
            //file = new File("C:/123.jpg");
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
            return file;
        } catch (IOException ioE) {
            throw ioE;
        } finally {
            if (null != outputStream) {
                outputStream.close();
            }
        }
    }

    /**
     * @Description: byte转base64
     * @author ljj
     * @date 2021/4/2
     */
    public static String turnByteToBase64(byte[] bytes) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(bytes);
    }

    /**
     * @Description: 删除临时文件
     * @author ljj
     * @date 2021/4/2
     */
    public static void deleteTempImageFile(File file) {
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    public static void  main(String[] args){
        String base64 = ImageZipUtil.turnByteToBase64(ImageZipUtil.compressPicForScale("C:\\微信图片_20210922133304.jpg", 190));
        System.out.println(base64);
        try {
            ImageZipUtil.turnBase64ToTempImageFile(base64,"jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

